<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Order;

class Settle extends \Service\Common\BaseModel
{
    protected $name = 'settle';

    //结算
    public function settleAll()
    {
        $list = $this->where(['settle_status' => 0])->select();
        if (!$list) {
            throw new \Exception("没有需要结算的订单");
        }

        try {
            $this->startTrans();
            foreach ($list as $row) {
                //佣金结算
                OE('order')->payCommissionCallback($row);
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //插入待结算记录
    public function addSettle($order)
    {
        $list = [];
        foreach ($order['goods'] as $data) {
            $fields = [
                'uid' => $data['uid'],
                'order_no' => $order['order_no'],
                'goods_id' => $data['goods_id'],
                'title' => $data['title'],
                'order_contribution' => $data['goods_contribution'],
                'settle_status' => 0,
                'settle_type' => $settle_type = $data['settlement_type'],
                'create_time' => date('Y-m-d H:i:s'),
            ];
            $insert_id = $this->add($fields);
            if (!$insert_id) {
                throw new \Exception("插入结算失败");
            }

            if ($settle_type == 1) {
                $list[] = array_merge($fields, ['id' => $insert_id]);
            }
        }
        return $list;
    }

    //设置已结算
    public function setSettle($id)
    {
        $update = $this->save([
            'id' => $id,
            'settle_status' => 1,
            'settle_time' => date('Y-m-d H:i:s'),
        ]);
        if ($update === false) {
            throw new \Exception("设置已结算失败");
        }
    }
}